package com.im

import android.graphics.BitmapFactory
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast

import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp

import com.im.ui.theme.ImClientTheme

// 注册活动
class RegActivity: AppCompatActivity() {
    /**
     * 界面布局。
     */
    @Composable
    fun Greeting() {
        var username by remember {
            mutableStateOf("")
        }
        val usernameFocusRequester = remember {
            FocusRequester()
        }
        var password by remember {
            mutableStateOf("")
        }
        val passwordFocusRequester = remember {
            FocusRequester()
        }
        var repassword by remember {
            mutableStateOf("")
        }
        val iconList = remember {
            mutableListOf<ImageBitmap>()
        }
        var iconIndex by remember {
            mutableIntStateOf(-1)
        }
        for (i in R.mipmap.normal00 .. R.mipmap.normal23) {
            val bitmap = BitmapFactory.decodeResource(resources, i).asImageBitmap()
            iconList.add(bitmap)
        }
        val context = LocalContext.current
        val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.normal00)
        val width = (bitmap.width * Const.REG_ACTIVITY_ICON_LIST_COLUMN_COUNT) / LocalDensity.current.density

        Column(Modifier
            .fillMaxSize()
            .padding(Const.REG_ACTIVITY_PADDING),
            Arrangement.Center,
            Alignment.Start
        ) {
            // "用户名"编辑框
            OutlinedTextField(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(Const.REG_ACTIVITY_CTRL_PADDING)
                    .focusRequester(usernameFocusRequester),
                label = {
                    Text(context.getString(R.string.IDS_USERNAME))
                },
                value = username,
                onValueChange = {
                    if (it.length <= Const.MAX_USERNAME_LEN) {
                        username = it
                    }
                },
                singleLine = true
            )

            // "密码"编辑框
            OutlinedTextField(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(Const.REG_ACTIVITY_CTRL_PADDING)
                    .focusRequester(passwordFocusRequester),
                label = {
                    Text(context.getString(R.string.IDS_PASSWORD))
                },
                value = password,
                onValueChange = {
                    if (it.length <= Const.MAX_PASSWORD_LEN) {
                        password = it
                    }
                },
                singleLine = true,
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Password,
                    imeAction = ImeAction.Done
                ),
                visualTransformation = PasswordVisualTransformation()
            )

            // "确认密码"编辑框
            OutlinedTextField(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(Const.REG_ACTIVITY_CTRL_PADDING),
                label = {
                    Text(context.getString(R.string.IDS_REPASSWORD))
                },
                value = repassword,
                onValueChange = {
                    if (it.length <= Const.MAX_PASSWORD_LEN) {
                        repassword = it
                    }
                },
                singleLine = true,
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Password,
                    imeAction = ImeAction.Done
                ),
                visualTransformation = PasswordVisualTransformation()
            )

            // "用户头像"标签
            Text(super.getString(R.string.IDS_USER_ICON), Modifier.padding(Const.REG_ACTIVITY_CTRL_PADDING))

            // 头像控件
            LazyVerticalGrid(
                GridCells.Fixed(Const.REG_ACTIVITY_ICON_LIST_COLUMN_COUNT),
                Modifier
                    .padding(Const.REG_ACTIVITY_CTRL_PADDING)
                    .width(width.dp)
            ) {
                itemsIndexed(iconList) { index, item ->
                    Image(
                        bitmap = iconList[index],
                        contentDescription = "",
                        colorFilter = if (iconIndex == index) ColorFilter.tint(Color.Gray, BlendMode.Darken) else null,
                        modifier = Modifier.clickable {
                            iconIndex = index
                        }
                    )
                }
            }

            // 按钮
            Row(Modifier.fillMaxWidth(), Arrangement.Center) {
                // "取消"按钮
                TextButton({
                    // 关闭活动
                    super.finish()
                }) {
                    Text(context.getString(android.R.string.cancel))
                }
                // "确定"按钮
                TextButton({
                    // 检查用户名是否为空
                    if (TextUtils.isEmpty(username)) {
                        Toast.makeText(context, R.string.IDS_USERNAME_EMPTY, Toast.LENGTH_LONG).show()
                        usernameFocusRequester.requestFocus()
                        return@TextButton
                    }

                    // 检查密码是否为空
                    if (TextUtils.isEmpty(password)) {
                        Toast.makeText(context, R.string.IDS_PASSWORD_EMPTY, Toast.LENGTH_LONG).show()
                        passwordFocusRequester.requestFocus()
                        return@TextButton
                    }

                    // 检查两次密码是否一致
                    if (password != repassword) {
                        Toast.makeText(context, R.string.IDS_PASSWORD_NOT_EQUAL, Toast.LENGTH_SHORT).show()
                        passwordFocusRequester.requestFocus()
                        return@TextButton
                    }

                    // 检查用户头像
                    if (iconIndex == -1) {
                        Toast.makeText(context, R.string.IDS_ICON_NOT_SELECT, Toast.LENGTH_SHORT).show()
                        return@TextButton
                    }

                    // 保存用户信息
                    val intent = super.getIntent()
                    val bundle = Bundle()
                    bundle.putString(Const.KEY_USERNAME, username)
                    bundle.putString(Const.KEY_PASSWORD, password)
                    bundle.putInt(Const.KEY_ICON_INDEX, iconIndex)
                    intent.putExtras(bundle)
                    super.setResult(RESULT_OK, intent)

                    // 关闭活动
                    super.finish()
                }) {
                    Text(context.getString(android.R.string.ok))
                }
            }
        }
    }

    /**
     * 创建事件的响应方法。
     * @param savedInstanceState    保存的实例状态
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.enableEdgeToEdge()

        // 设置标题
        super.setTitle(R.string.IDS_REG)

        // 设置内容
        this.setContent {
            ImClientTheme {
                this.Greeting()
            }
        }
    }
}
